package com.inco.cloud.common.exception;
import com.alibaba.fastjson.JSON;
import com.inco.cloud.common.model.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author hjljy
 * Oauth2异常信息返回处理
 */
@Component
@Slf4j
public class CustomAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        ReturnT re = new ReturnT();
        if (authException instanceof BadCredentialsException){
            //如果是client_id和client_secret相关异常 返回自定义的数据格式
            response.setStatus(HttpStatus.OK.value());
            re.setStatus(HttpStatus.OK.value());
            re.setMsg("客户端相关异常");
            log.error("Authentication异常: [{}], [{}], [{}]", request.getRequestURI(), authException.getMessage(), authException);
        }else if(authException instanceof InsufficientAuthenticationException){
            //如果是没有携带token 401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            re.setStatus(HttpStatus.UNAUTHORIZED.value());
            re.setMsg("Token失效，请重新登录");
        }else {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            re.setStatus(500);
            re.setMsg(authException.getMessage());
            log.error("Authentication异常: [{}], [{}], [{}]", request.getRequestURI(), authException.getMessage(), authException);
        }
        out.write(JSON.toJSONString(re));
    }
}

